package com.osfw.system.service.manage.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.osfw.framework.constants.Constants;
import com.osfw.framework.constants.UserConstants;
import com.osfw.framework.core.domain.Ztree;
import com.osfw.framework.utils.StringUtils;
import com.osfw.system.entity.manage.SysMenu;
import com.osfw.system.entity.manage.SysRole;
import com.osfw.system.entity.manage.SysRoleMenu;
import com.osfw.system.entity.manage.SysUser;
import com.osfw.system.mapper.manage.SysMenuMapper;
import com.osfw.system.mapper.manage.SysRoleMenuMapper;
import com.osfw.system.service.manage.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 菜单 业务层处理
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {
    public static final String PREMISSION_STRING = "perms[\"{0}\"]";

    @Resource
    private SysMenuMapper menuMapper;

    @Resource
    private SysRoleMenuMapper roleMenuMapper;

    @Override
    public List<SysMenu> selectUsedMenus(Long userId) {
        List<SysMenu> menus = new LinkedList<SysMenu>();
        // 管理员显示所有菜单信息
        if (SysUser.isAdmin(userId)) {
            menus = menuMapper.selectUsedMenuNormalAll(new SysMenu());
        } else {
            SysMenu menu = new SysMenu();
            menu.getParams().put("userId", userId);
            menus = menuMapper.selectUsedMenusByUserId(menu);
        }
        return menus;
    }

    /**
     * 根据用户查询菜单
     *
     * @param userId 用户信息
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> selectMenusByUser(SysMenu menu, Long userId) {
        List<SysMenu> menus = new LinkedList<SysMenu>();
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        // 管理员显示所有菜单信息
        if (SysUser.isAdmin(userId)) {
            menus = menuMapper.selectMenuNormalAll(menu);
        } else {
            menu.getParams().put("userId", userId);
            menus = menuMapper.selectMenusByUserId(menu);
        }
        return getChildPerms(menus, menu.getParentId().longValue());
    }

    /**
     * 查询菜单集合
     *
     * @return 所有菜单信息
     */
    @Override
    public List<SysMenu> selectMenuList(SysMenu menu, SysUser user) {
        List<SysMenu> menuList = null;
        if (user.isAdmin()) {
            menuList = menuMapper.selectMenuList(menu);
        } else {
            menu.getParams().put("userId", user.getUserId());
            menuList = menuMapper.selectMenuListByUserId(menu);
        }
        return menuList;
    }

    /**
     * 查询菜单列表（直属下级菜单）
     * <p>
     * menu 系统菜单对象
     * userId 当前登录用户ID
     *
     * @return java.util.List<SysMenu>
     */
    @Override
    public List<SysMenu> selectImmediateChildrenMenuList(SysMenu menu, SysUser user) {
        List<SysMenu> menuList = null;
        if (menu != null && StringUtils.isEmpty(menu.getMenuName()) && StringUtils.isEmpty(menu.getVisible())) {
            if (menu.getParentId() == null) {
                menu.setParentId(0l);
            }
            if (user.isAdmin()) {
                menuList = menuMapper.selectImmediateChildrenMenuList(menu);
            } else {
                menu.getParams().put("userId", user.getUserId());
                menuList = menuMapper.selectImmediateChildrenMenuListByUserId(menu);
            }
        } else {
            menu.setMenuType("F");
            menuList = selectMenuList(menu, user);
        }
        return menuList;
    }

    /**
     * 查询菜单集合
     *
     * @return 所有菜单信息
     */
    @Override
    public List<SysMenu> selectMenuAll(Long userId) {
        List<SysMenu> menuList = null;
        if (SysUser.isAdmin(userId)) {
            menuList = menuMapper.selectMenuAll();
        } else {
            menuList = menuMapper.selectMenuAllByUserId(userId);
        }
        return menuList;
    }

    /**
     * 查询菜单集合
     *
     * @return 所有菜单信息
     */
    public List<SysMenu> selectMenuImmediateChild(SysUser user, SysMenu menu) {
        List<SysMenu> menuList = null;
        if (user.isAdmin()) {
            menuList = menuMapper.selectMenuImmediateChild(menu);
        } else {
            menu.getParams().put("userId", user.getUserId());
            menuList = menuMapper.selectMenuImmediateChildByUserId(menu);
        }
        return menuList;
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectPermsByUserId(Long userId) {
        List<String> perms = menuMapper.selectPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 根据角色ID查询权限
     *
     * @param roleId 角色ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectPermsByRoleId(Long roleId) {
        List<String> perms = menuMapper.selectPermsByRoleId(roleId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 根据角色ID查询菜单
     *
     * @param role 角色id
     * @return 菜单列表
     */
    @Override
    public List<Ztree> roleMenuTreeData(SysRole role, SysUser user) {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        List<SysMenu> menuList = selectMenuAll(user.getUserId());
        if (StringUtils.isNotNull(role) && StringUtils.isNotNull(role.getRoleId())) {
            List<String> roleMenuList = menuMapper.selectMenuTree(role.getRoleId());
            ztrees = initZtree(menuList, roleMenuList, true);
        } else {
            ztrees = initZtree(menuList, null, true);
        }
        return ztrees;
    }

    /**
     * 查询所有菜单
     *
     * @return 菜单列表
     */
    @Override
    public List<Ztree> menuTreeData(Long userId) {
        List<SysMenu> menuList = selectMenuAll(userId);
        List<Ztree> ztrees = initZtree(menuList);
        return ztrees;
    }

    /**
     * 查询所有菜单（直属下级）
     *
     * @return 菜单列表
     */
    @Override
    public List<Ztree> menuTreeDataImmediateChild(SysUser user, SysMenu menu) {
        if (menu != null && menu.getParentId() == null) {
            menu.setParentId(0l);
        }
        List<SysMenu> menuList = selectMenuImmediateChild(user, menu);
        List<Ztree> ztrees = initZtree(menuList);
        return ztrees;
    }

    /**
     * 查询系统所有权限
     *
     * @return 权限列表
     */
    @Override
    public LinkedHashMap<String, String> selectPermsAll(Long userId) {
        LinkedHashMap<String, String> section = new LinkedHashMap<>();
        List<SysMenu> permissions = selectMenuAll(userId);
        if (StringUtils.isNotEmpty(permissions)) {
            for (SysMenu menu : permissions) {
                section.put(menu.getUrl(), MessageFormat.format(PREMISSION_STRING, menu.getPerms()));
            }
        }
        return section;
    }

    /**
     * 对象转菜单树
     *
     * @param menuList 菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<SysMenu> menuList) {
        return initZtree(menuList, null, false);
    }

    /**
     * 对象转菜单树
     *
     * @param menuList     菜单列表
     * @param roleMenuList 角色已存在菜单列表
     * @param permsFlag    是否需要显示权限标识
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<SysMenu> menuList, List<String> roleMenuList, boolean permsFlag) {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleMenuList);
        for (SysMenu menu : menuList) {
            Ztree ztree = new Ztree();
            ztree.setId(menu.getMenuId());
            ztree.setpId(menu.getParentId());
            ztree.setName(transMenuName(menu, permsFlag));
            ztree.setTitle(menu.getMenuName());
            // 是否父节点
            ztree.setIsParent("1".equals(menu.getIsParent())?"true":"false");
            if (isCheck) {
                ztree.setChecked(roleMenuList.contains(menu.getMenuId() + menu.getPerms()));
            }
            ztrees.add(ztree);
        }
        return ztrees;
    }

    private String transMenuName(SysMenu menu, boolean permsFlag) {
        StringBuffer sb = new StringBuffer();
        sb.append(menu.getMenuName());
        if (permsFlag) {
            sb.append(" <span class='am-text-default'>&nbsp;&nbsp;&nbsp;" + menu.getPerms() + "</span>");
        }
        return sb.toString();
    }

    /**
     * 删除菜单管理信息
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    @Transactional
    public boolean deleteMenuById(Long menuId) {
        SysMenu menu = selectMenuById(menuId);
        int count = selectCountMenuByParentId(menu.getParentId());
        if(count == 1){
            SysMenu parentMenu = new SysMenu();
            parentMenu.setMenuId(menu.getParentId());
            parentMenu.setIsParent("0");
            updateById(parentMenu);
        }
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.and(wrapper -> {
            wrapper.eq(SysMenu::getMenuId, menuId);
            wrapper.or();
            wrapper.eq(SysMenu::getParentId, menuId);
        });
        return remove(queryWrapper);
    }

    /**
     * 根据菜单ID查询信息
     *
     * @param menuId 菜单ID
     * @return 菜单信息
     */
    @Override
    public SysMenu selectMenuById(Long menuId) {
        return menuMapper.selectMenuById(menuId);
    }

    /**
     * 查询子菜单数量
     *
     * @param parentId 父级菜单ID
     * @return 结果
     */
    @Override
    public int selectCountMenuByParentId(Long parentId) {
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysMenu::getParentId, parentId);
        return count(queryWrapper);
    }

    /**
     * 查询菜单使用数量
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public int selectCountRoleMenuByMenuId(Long menuId) {
        LambdaQueryWrapper<SysRoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleMenu::getMenuId, menuId);
        return roleMenuMapper.selectCount(queryWrapper);
    }

    /**
     * 新增保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    @Transactional
    public boolean insertMenu(SysMenu menu) {
        int count = selectCountMenuByParentId(menu.getParentId());
        if(count == 0) {
            SysMenu parentMenu = new SysMenu();
            parentMenu.setMenuId(menu.getParentId());
            parentMenu.setIsParent("1");
            updateById(parentMenu);
        }
        menu.setIsParent("0");
        return save(menu);
    }

    /**
     * 修改保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    @Transactional
    public boolean updateMenu(SysMenu menu) {
        SysMenu old = selectMenuById(menu.getMenuId());
        if(old.getParentId().longValue() != menu.getParentId().longValue()){
            int old_count = selectCountMenuByParentId(old.getParentId());
            if(old_count == 1) {
                SysMenu parentMenu = new SysMenu();
                parentMenu.setMenuId(old.getParentId());
                parentMenu.setIsParent("0");
                updateById(parentMenu);
            }
            int count = selectCountMenuByParentId(menu.getParentId());
            if(count == 0) {
                SysMenu parentMenu = new SysMenu();
                parentMenu.setMenuId(menu.getParentId());
                parentMenu.setIsParent("1");
                updateById(parentMenu);
            }
        }
        return updateById(menu);
    }

    /**
     * 校验菜单名称是否唯一
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public String checkMenuNameUnique(SysMenu menu) {
        Long menuId = StringUtils.isNull(menu.getMenuId()) ? -1L : menu.getMenuId();
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysMenu::getMenuName, menu.getMenuName());
        queryWrapper.eq(SysMenu::getParentId, menu.getParentId());
        List<SysMenu> menus = list(queryWrapper);
        if(menus != null && !menus.isEmpty()){
            if (StringUtils.isNotNull(menus.get(0)) && menus.get(0).getMenuId().longValue() != menuId.longValue()) {
                return Constants.NOT_UNIQUE;
            }
        }
        return Constants.UNIQUE;
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list     分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<SysMenu> getChildPerms(List<SysMenu> list, Long parentId) {
        List<SysMenu> returnList = new ArrayList<SysMenu>();
        for (Iterator<SysMenu> iterator = list.iterator(); iterator.hasNext(); ) {
            SysMenu t = (SysMenu) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId().longValue() == parentId.longValue()) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursionFn(List<SysMenu> list, SysMenu t) {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenu tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t) {
        List<SysMenu> tlist = new ArrayList<SysMenu>();
        Iterator<SysMenu> it = list.iterator();
        while (it.hasNext()) {
            SysMenu n = (SysMenu) it.next();
            if (n.getParentId().longValue() == t.getMenuId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenu> list, SysMenu t) {
        return getChildList(list, t).size() > 0;
    }
}
